package com.yan.test;

import jodd.http.HttpBrowser;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.*;

/**
 * Created by yanl_ on 2018/2/1.
 */
public class HttpHelper {

    private static Logger logger = LoggerFactory.getLogger(HttpHelper.class);


    //获取rabbit 回调相关信息
    public static String sendCallbackGet(String vhost, String userName, String password) {
        String result = "";
        logger.info("获取rabbit username:{} vhost:{}", userName, vhost);
        try {
            String url = "10.13.0.1";
            int port = 15672;
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpClientContext context = HttpClientContext.create();
            org.apache.http.HttpHost targetHost = new org.apache.http.HttpHost(url, port, "http");

            //认证提供者
            org.apache.http.client.CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new org.apache.http.auth.AuthScope(targetHost.getHostName(), targetHost.getPort()),
                    new UsernamePasswordCredentials(userName, password));
            //基础认证缓存
            AuthCache authCache = new BasicAuthCache();

            context.setCredentialsProvider(credsProvider);
            context.setAuthCache(authCache);
            HttpGet httpget = new HttpGet("/api/queues/#" + vhost);

            CloseableHttpResponse response = httpclient.execute(targetHost, httpget, context);
            logger.info("HTTP Request response {}", response);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
                logger.info("request url:{} return msg:{}", targetHost, result);
            } else {
                logger.info("HTTP Request is not success, Response code is {} request url:{},httpget:{}", response.getStatusLine().getStatusCode(),
                        targetHost, httpget);
            }
        } catch (Exception e) {
            logger.error("vhost:{} sendGet exception:{}", vhost, e.getMessage(), e);
        }
        return result;
    }


    public static Object getData(String filePath, int type) {

        try {
            List<String> list = FileUtils.readLines(new File(filePath), "utf-8");
            if (type == 1) {
                Set<String> set = new HashSet<String>();
                set.addAll(list);
                System.out.println(set.size());

                return set;
            }

            if (type == 2) {
                return list;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    public void test() {
        getData("D://paymentId.txt", 1);
        getData("D://username.txt", 1);
        getData("D://id.txt", 1);

        List<String> paymentIdList = (List<String>) getData("D://paymentId.txt", 2);
        List<String> idList = (List<String>) getData("D://id.txt", 2);

        List<String> usernameList = (List<String>) getData("D://username.txt", 2);
        Set<String> usernameSet = new HashSet<String>();
        usernameSet.addAll(usernameList);
        List<String> usernameList2 = new ArrayList<String>();
        usernameList2.addAll(usernameSet);

        List<Collection> resultList = Arrays.asList(CollectionUtils.intersection(usernameList, usernameList2));
        System.out.println("交集:" + CollectionUtils.intersection(paymentIdList, idList));
        System.out.println("交集:" + resultList + "  size:" + CollectionUtils.intersection(usernameList, usernameList2).size());


        List<String> idaList = (List<String>) getData("D://102笔差异.txt", 2);
        getData("D://102笔差异.txt", 1);
        System.out.println("==============" + idaList.size() + "=========");

        String result = StringUtils.join(idaList, "','");
        System.out.println(idaList + "\n");

        System.out.println("================================");
        System.out.println(result);


        System.out.println("================================");


        List<String> pamentIdList = (List<String>) getData("D://paymentId.txt", 2);
        String resultPamentId = StringUtils.join(pamentIdList, "','");
        System.out.println(resultPamentId);
    }


    public static void main(String[] args) {
        //    HttpHelper.sendCallbackGet("/koukuan_rd", "zhanglifeng", "gBYCYMtEMw517k6b");


//        HttpResponse response = HttpRequest
//                .get("http://10.13.0.1:15672")
//                .body("{'$user[userId, screenName] = /user/get-user-by-id' : {'userId':'10194'}}")
//                .basicAuthentication("zhanglifeng", "gBYCYMtEMw517k6b")
//                .send();
//
//        System.out.println(response.bodyText());


        HttpBrowser browser = new HttpBrowser();

        HttpRequest request = HttpRequest
                .post("http://182.23.65.25:31555/admin/login!process.payin").form("username", "dr-mon035", "password", "drmon2017!");


        browser.sendRequest(request);
        String page = browser.getPage();
        System.out.println(page);


        String statusSettlement = "-1";
        String vaType = "-1";
        String vaStatus = "1";
        String dateTimeType = "PAYMENT_DATE";
        String gmt = "Asia/Jakarta";
        String reportType = "2";

        String pull_date = "2017-12-18";
        StringBuilder stringBuilder = new StringBuilder("http://182.23.65.25:31555/admin/report!downloadReportVATransaction.payin?");
        stringBuilder.append("statusSettlement").append("=").append(statusSettlement).append("&")
                .append("startDateTime").append("=").append(pull_date + "%2000:00").append("&")
                .append("vaType").append("=").append(vaType).append("&")
                .append("vaStatus").append("=").append(vaStatus).append("&")
                .append("dateTimeType").append("=").append(dateTimeType).append("&")
                .append("endDateTime").append("=").append(pull_date + "%2023:59").append("&")
                .append("gmt").append("=").append(gmt).append("&")
                .append("reportType").append("=").append(reportType);

        InputStream is = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        int responseCode = 0;
        try {
            String execlPath = "D:\\" + "INTRAJASA_Debit_" + pull_date + ".xlsx";
            FileUtils.touch(new File(execlPath));


            HttpRequest request1 = HttpRequest.post(stringBuilder.toString()).accept("utf-8");
            browser.sendRequest(request1).unzip().bodyText();
            String context = browser.getPage();
            String ttt1 = request1.send().bodyText();
            System.out.println();
            FileUtils.writeStringToFile(new File(execlPath), context);
            System.out.println("=======================================================");
            System.out.println("context:" + context);
        } catch (IOException e) {
            logger.error("intrajasa down lliquidation execl responseCode{} error:{}", responseCode, e);

        } finally {

            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(is);

        }

    }
}
